<?php

namespace addons\fzdc;

use app\common\library\Menu;
use think\Addons;
use think\Exception;
use think\Loader;
use think\Hook;

/**
 * 插件
 */
class Fzdc extends Addons
{

    /**
     * 应用初始化
     */
    public function appInit()
    {
        require_once __DIR__.'/helper.php';
        //添加命名空间
        if (!class_exists('\zhongwu\protocol\RpcClient')) {
            Loader::addNamespace('zhongwu', ADDON_PATH . 'fzdc' . DS . 'library' . DS . 'zhongwu' . DS . 'printer' . DS);
        }
        if (!class_exists('\App\Config\YlyConfig')) {
            Loader::addNamespace('App', ADDON_PATH . 'fzdc' . DS . 'library' . DS . 'yly-openapi' . DS . 'yly-openapi-sdk' . DS . 'Lib' . DS);
        }
        if (!class_exists("Grafika\Grafika")) {
            Loader::addNamespace('Grafika', ADDON_PATH . 'fzdc' . DS . 'library' . DS . 'Grafika' . DS);
        }
        Hook::add('fzdc_distribution', 'addons\fzdc\behavior\DistributionHook');
    }

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu=[];
        $config_file= ADDON_PATH ."fzdc" . DS.'config'.DS. "menu.php";
        if (is_file($config_file)) {
            $menu = include $config_file;
        }
        if($menu){
            Menu::create($menu);
        }
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        $info=get_addon_info('fzdc');
        Menu::delete(isset($info['first_menu'])?$info['first_menu']:'fzdc');
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        $info = get_addon_info('fzdc');
        Menu::enable(isset($info['first_menu']) ? $info['first_menu'] : 'fzdc');
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        $info=get_addon_info('fzdc');
        Menu::disable(isset($info['first_menu'])?$info['first_menu']:'fzdc');
    }
	
	/**
     * 插件更新方法
     */
    public function upgrade()
    {
        // 更新菜单
        $menu = self::getMenu();
        Menu::upgrade('fzdc', $menu['new']);

        return true;
    }

    private static function getMenu()
    {
        $newMenu = [];
        $config_file = ADDON_PATH . "fzdc" . DS . 'config' . DS . "menu.php";
        if (is_file($config_file)) {
            $newMenu = include $config_file;
        }
        $oldMenu = AuthRule::where('name', 'like', "venue%")->select();
        $oldMenu = array_column($oldMenu, null, 'name');
        return ['new' => $newMenu, 'old' => $oldMenu];
    }
    
}
